-- DungeonFountainM
-- Created by chengb Mar/9/2015
-- 地牢幸运喷泉

module("DungeonFountainM", package.seeall);

-- 幸运喷泉配置表
local fountainTable = {};

-- 幸运喷泉奖励列表
local fountainBonusList = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    local dungeon_fountain_CSV = get_dungeon_fountain_CSV();
    for i = 1, #dungeon_fountain_CSV do
        local id = dungeon_fountain_CSV[i].id;
        fountainTable[id] = dungeon_fountain_CSV[i];
    end

    fountainBonusList = table.values(fountainTable);

    -- 按照id升序，为了和服务器随机时一致
    table.sort(fountainBonusList, function(a, b) return a.id < b.id; end);

    dungeon_fountain_CSV = nil;
end

-- 初始化
function init()
    loadCsv();
end

-- 检索配置
function query(id, path)
    local m = fountainTable[id];

    if not m or path == "" or not path then
        return m;
    end

    return m[path];
end

--------------------------
-- 根据随机种子抽取一种奖励
-- @param seed 随机种子
function fetchBonusBySeed(seed)
    local bonus = fetchElemBySeed(fountainBonusList, seed);
    return bonus;
end

-- 生成幸运喷泉奖励
function generateBonus()
    local bonus = FormulaM.invoke("FETCH_FOUNTAIN_BONUS");

    printTable(bonus, "幸运喷泉奖励已生成");

    return bonus;
end

--------------------------
-- 领取幸运喷泉奖励
-- @param pos  喷泉格子的位置
function takeBonus(pos)
    if true ~= canTakeBonus(pos) then
        -- 经判断，不能领取
        return false;
    end

    local grid = DungeonM.getGridByPos(pos);
    local bonus = grid.bonus;

    local needSP = calcSPCost();

    -- 扣除探索点
    if not ME.user:costAttrib("search_point", needSP) then
        -- 探索点扣除失败
        trace("DungeonFountainM", "扣除探索点失败了。");
        return false;
    end

    -- 格子失效
    grid:changeState(GRID_STATE_DISABLE);

    -- 执行奖励
    BonusM.doBonus(bonus, "fountain_bonus");

    -- 抛出领取奖励事件
    EventMgr.fire(event.TAKE_FOUNTAIN_BONUS, { ["bonus"] = bonus, ["pos"] = pos, });

    -- 通知建筑事件完成
    EventMgr.fire(event.BUILDING_EVENT_DONE, {["pos"] = pos,});

    return true;
end

-- 计算领取幸运喷泉奖励的探索点消耗
function calcSPCost()
    return FormulaM.invoke("CALC_FOUNTAIN_BONUS_COST_SP", ME.user);
end

-- 判断能否领取喷泉奖励
function canTakeBonus(pos)
    if not DungeonM.checkDungeonAction() then
        -- 经检测，不允许执行地牢行为
        return false;
    end

    local grid = DungeonM.getGridByPos(pos);
    if not grid then
        trace("DungeonFountainM", "格子(%d)不存在。", pos);
        return false;
    end

    local bonus = grid.bonus;
    if not bonus then
        -- 奖励尚未生成
        trace("DungeonFountainM", "喷泉奖励尚未生成。");
        return false;
    end

    if ME.user:queryAttrib("search_point") < calcSPCost() then
        -- 探索点不足
        return "sp_lack";
    end

    return true;
end





